<?php
$isReloadable = true;
require_once("../../../pers/inc.config.php");
require_once('../../_inc/inc.session.php');
require_once('../../_inc/funct.html.php');
require_once('../../_inc/funct.tabDati.php');

if (reqVar('azione') == 'calcola') {
	$msgPag = calcRatGlob();
} 
if (reqVar('azione') == 'reset') {
	$msgPag = resetRatGlob();
} 
if (reqVar('azione') == 'elimina') {
	$msgPag = elimRatGlob();
} 
$modoNotching = '';
if (reqVar('azione') == 'regnot') {
	$msgPag = registraNotching($modoNotching);
} 


$sSql = "SELECT r.* "
	.", rb.id_bil, rb.id_bil_2, rb.id_bil_3, id_mod_rbil "
	.", rb.peso AS rb_peso, rb.punteggio AS rb_punteggio, rb.sigla AS rb_sigla  "
	.", rb.cod_mod_rbil, rb.descr_mod_rbil, rb.str_def_dati, str_dati"
	.", rq.peso AS rq_peso, rq.punteggio AS rq_punteggio, rq.sigla AS rq_sigla  "
	.", rq.cod_mod_rque, rq.descr_mod_rque, rq.str_que, id_mod_rque "
	.", s.descr AS s_descr "
	." FROM rgl_rating r"
	." LEFT JOIN rgl_ratbil rb ON rb.id_rating = r.id_rating "
	." LEFT JOIN rgl_ratque rq ON rq.id_rating = r.id_rating "
	." LEFT JOIN rgl_settore s ON s.cod_sett = r.cod_sett "
	." WHERE r.id_rating = ".reqVarInt('id');
$objDB->query($sSql,'selRec');
if (!$acRat = $objDB->fetch('selRec')) {
	backOnErr("rglobVis - var. id '".reqVar('id')."' mancante o errato - $sSql");
}

$aDefDati = (empty($acRat['str_def_dati'])) ? array() : unsgzu($acRat['str_def_dati']);
$aVar = (empty($acRat['str_dati'])) ? array() : unsgzu($acRat['str_dati']);
$aQue = (empty($acRat['str_que'])) ? array() : unsgzu($acRat['str_que']);

$sSql = "SELECT * FROM rgl_azienda " .
		" WHERE id_azienda = ".$acRat['id_azienda'];
$objDB->query($sSql,'selAnag');
$acAnag = $objDB->fetch('selAnag');
//dbg_($acAnag);
$_REQUEST = array_merge($acAnag,$_REQUEST);

$sCmdL = '';
$sCmdL .= "<a class='cmd1' href=\"rglobPdf.php?id=".reqVar('id')."&xsn=".XSN."\" target='_blank'>PDF</a>";
$sCmdL .= "&nbsp;&nbsp;&nbsp;";
$sCmdL .= "<a class='cmd1' href=\"".RGL_URL_LOG_DIR."/ratg_".reqVar('id')
	.".csv\" target='_blank'>csv calcoli</a>";

$sCmdR = '';
if ($acRat['stato']=='creato') {
	$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	$sCmdR .= "<a class='cmd1' href=\"javascript:confCalcola();\">calcola</a>";
	$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	$sCmdR .= "<a class='cmd1' href=\"javascript:confElimina();\">elimina</a>";
	$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
	$sCmdR .= "<a class='cmd1' href=\"rglobMod.php?id=".reqVar('id')."&xsn=".XSN."\">modifica</a>";
	$sCmdR .= cmdTorna('torna');
} else  {
	if (reqvar('modoNotching')=='S') {
		$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$sCmdR .= "<a class='cmd1' href=\"javascript:submAz('regnot');\">registra notching</a>";		
		$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$sCmdR .= "<a class='cmd1' href=\"javascript:submAz('reload');\">annulla</a>";		
	} else {
		$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$sCmdR .= "<a class='cmd1' href=\"javascript:setNotching();\">notching</a>";
		$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$sCmdR .= "<a class='cmd1' href=\"javascript:confRicalcola();\">ri-calcola</a>";
		$sCmdR .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		$sCmdR .= "<a class='cmd1' href=\"javascript:confReset();\">reset</a>";
		$sCmdR .= cmdTorna('torna');
	}
}

$aOpzTesta = array();

testaHtml('', $msgPag, 'ratg',$aOpzTesta);
?>
<script type="text/javascript">
<!--
function submAz(az) {
	document.frm1.azione.value = az;
	document.frm1.submit();
}
function setNotching() {
	document.frm1.modoNotching.value = 'S';
	document.frm1.submit();
}
function confElimina() {
	if (confirm("Confermi eliminazione ?")) {
		submAz('elimina');
	}
}
function confCalcola() {
	if (confirm("Confermi calcolo ?")) {
		submAz('calcola');
	}
}
function confRicalcola() {
	if (confirm("Confermi ri-calcolo ?")) {
		submAz('calcola');
	}
}
function confReset() {
	if (confirm("Confermi reset ?")) {
		submAz('reset');
	}
}
//-->
</script>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
			<? echo $sCmdL; ?>
      </td>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo getHtmlForm('frm1','',array('enctype'=>true));
echo getHtmlHidden('azione','...');
echo getHtmlHidden('xsn',XSN);
echo getHtmlHidden('id');
echo getHtmlHidden('modoNotching',$modoNotching);
?>
<table class="tab1" border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
	<?=getHtmlRigaRif();?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Anagrafica Azienda</td>
   </tr>
	<?
$aCamForm = array();
require("../cbil/_inc/const.campiAnag.php");
$aVarExt['href_rag_soc'] = "../cbil/anagVis.php?id=".$acRat['id_azienda']."&xsn=".XSN;
echo getHtmlCampiForm($aCamForm,'vis',$aVarExt);
?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Rating globale</td>
   </tr>
   <tr>
      <td class="lab1" colspan='1' align='left'>Id.</td>
      <td class="txt1" colspan='1' align='right'><?=$acRat['id_rating']?></td>
      <td class="lab1" colspan='2' align='left'>Data rif. </td>
      <td class="txt1" colspan='2' align='left'>
      	<? echo YMD2DMY($acRat['data_rif']);?>
      </td>
      <td class="lab1" colspan='2' align='left'>Modello </td>
      <td class="txt1" colspan='8' align='left'>
      	<? echo $acRat['descr_mod_rglob'];?>
      </td>
      <td class="lab1" colspan='2' align='left'>Stato</td>
      <td class="txt1" colspan='2' align='left'>
      	<? echo ($acRat['sigla_calc']=='')?'da calcolare':'calcolato';?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Descrizione </td>
      <td class="txt1" colspan='16' align='left'>
      	<? echo $acRat['descr'];?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Settore </td>
      <td class="txt1" colspan='13' align='left'>
      	<? echo $acRat['cod_sett']." - ".$acRat['s_descr'];?>
      </td>
      <td class="lab1" colspan='2' align='left'>Punteggio calc.</td>
      <td class="txt1" colspan='1' align='right'><? echo $acRat['punt_calc'];?>&nbsp;</td>
   </tr>
<?
if ($acRat['sigla_calc']!='') {
	$sqlSel = "SELECT * FROM rgl_puntglob " 
			." WHERE id_mod_rglob = ".$acRat['id_mod_rglob']
			." AND sigla = '".addslashes($acRat['sigla_calc'])."' ";
	$objDB->query($sqlSel,'selRec');
	$sStyle = '';
	if ($acP = $objDB->fetch('selRec')) {
		if ($acP['colore']=='verde') {
			$sStyle = "color:".RGL_COLORE_VERDE.";";
		} elseif ($acP['colore']=='giallo') {
			$sStyle = "color:".RGL_COLORE_GIALLO.";";
		} else {
			$sStyle = "color:".RGL_COLORE_ROSSO.";";
		}
	} 
	?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Rating globale calcolato</td>
      <td class="txt1" colspan='2' align='center'
      	style='font-size:16pt;font-weight:bold;<?=$sStyle?>'><? echo $acRat['sigla_calc'];?></td>
      <td class="txt1" colspan='14' align='left'><? echo $acP['descr_estesa'];?></td>
   </tr>
<?
	if (reqVar('modoNotching')=='S') {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Nota dell'analista</td>
      <td class="txt1" colspan='16' align='left'>
      	<? 
      	reqDef('nota_analista',$acRat['nota']);
      	echo getHtmlTextArea('nota_analista',150,5);
      	?>
      </td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Notching</td>
      <td class="txt1" colspan='16' align='left'>
      	<? 
      	$aNotch = array(-3=>'-3',-2=>'-2',-1=>'-1',0=>'0',1=>'+1',2=>'+2',3=>'+3');
			//dbg_($_REQUEST);
			reqDef('notching',$acRat['notching']);
      	echo getHtmlRadio('notching',$aNotch);
      	?>
      </td>
   </tr>
<?	
	} elseif($acRat['nota']!='') {
		$sqlSel = "SELECT * FROM rgl_puntglob " 
				." WHERE id_mod_rglob = ".$acRat['id_mod_rglob']
				." AND sigla = '".addslashes($acRat['sigla'])."' ";
		$objDB->query($sqlSel,'selRec');
		$sStyle = '';
		if ($acP = $objDB->fetch('selRec')) {
			if ($acP['colore']=='verde') {
				$sStyle = "color:".RGL_COLORE_VERDE.";";
			} elseif ($acP['colore']=='giallo') {
				$sStyle = "color:".RGL_COLORE_GIALLO.";";
			} else {
				$sStyle = "color:".RGL_COLORE_ROSSO."0;";
			}
		} 
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Nota dell'analista</td>
      <td class="txt1" colspan='15' align='left'><? echo getHtmlViewNote($acRat['nota']);?></td>
      <td class="txt1" colspan='1' align='right'><? printf('%+d', $acRat['notching']);?>&nbsp;</td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Rating globale</td>
      <td class="txt1" colspan='2' align='center'
      	style='font-size:16pt;font-weight:bold;<?=$sStyle?>'><? echo $acRat['sigla'];?></td>
      <td class="txt1" colspan='14' align='left'><? echo $acP['descr_estesa'];?></td>
   </tr>
<?
	}
}
if ($acRat['cod_mod_rbil'] != '') {
?>
   <tr>
      <td class="tit1" colspan='16' align='center'>Rating Bilancio</td>
      <td class="tit1" colspan='4' align='center'>Sezioni</td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Modello</td>
      <td class="txt1" colspan='8' align='left'>
      	<? echo $acRat['descr_mod_rbil'];?>
      </td>
      <td class="lab1" colspan='1' align='left'>Peso</td>
      <td class="txt1" colspan='1' align='left'>
      	<? echo $acRat['rb_peso'];?>
      <td class="lab1" colspan='1' align='left'>Punt.</td>
      <td class="txt1" colspan='1' align='left'>
      	<? echo $acRat['rb_punteggio'];?>
      </td>
      <td class="txt1" colspan='4' align='left' rowspan='4' valign='top' >
      	<? 
	if ($acRat['rb_sigla']!='') {
      	echo "<div style='padding:3;'><a class='txt1' href='rbilBilCeeVis.php?id=".$acRat['id_rating']
      		."&xsn=".XSN."'>A. bilancio UE</a></div>\n";
      	echo "<div style='padding:3;'><a class='txt1' href='rbilBilRicVis.php?id=".$acRat['id_rating']
      		."&xsn=".XSN."'>B. bilancio riclassificato</a></div>\n";
      	echo "<div style='padding:3;'><a class='txt1' href='rbilRenFinVis.php?id=".$acRat['id_rating']
      		."&xsn=".XSN."'>C. rendiconto finanziario</a></div>\n";
			echo "<div style='padding:3;'><a class='txt1' href='rbilIndiciVis.php?id=".$acRat['id_rating']
      		."&xsn=".XSN."'>D. indici di bilancio</a></div>\n";
	} else {
      	echo "<div style='padding:3;'><a class='txt1' href='../cbil/bilCeeVis.php?id=".$acRat['id_bil']."&idp=".$acRat['id_bil_2']
      		."&xsn=".XSN."'>A. bilancio UE</a></div>\n";
      	echo "<div style='padding:3;'><a class='txt1' href='../cbil/bilRicVis.php?id=".$acRat['id_bil']."&idp=".$acRat['id_bil_2']
      		."&xsn=".XSN."'>B. bilancio riclassificato</a></div>\n";
      	echo "<div style='padding:3;'><a class='txt1' href='../cbil/renFinVis.php?id=".$acRat['id_bil']."&idp=".$acRat['id_bil_2']
      		."&xsn=".XSN."'>C. rendiconto finanziario</a></div>\n";
			echo "<div style='padding:3;'><a class='txt1' href='../cbil/indiciVis.php?id=".$acRat['id_bil']."&idp=".$acRat['id_bil_2']
      		."&cod_sett=".$acRat['cod_sett']."&xsn=".XSN."'>D. indici di bilancio</a></div>\n";
		
	}
			?>
      </td>
   </tr>
<?
	if (isset($aVar['B_DATA_RIF'])) {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Bilancio di riferimento </td>
      <td class="txt1" colspan='12' align='left'>
      	<? echo YMD2DMY($aVar['B_DATA_RIF'])." - ".$aVar['B_DESCR_BIL'];?>
      </td>
   </tr>
<?
	}
	if (isset($aVar['C_DATA_RIF'])) {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Bilancio precedente </td>
      <td class="txt1" colspan='12' align='left'>
      	<? echo YMD2DMY($aVar['C_DATA_RIF'])." - ".$aVar['C_DESCR_BIL'];?>
      </td>
   </tr>
<?
	}
	if (isset($aVar['D_DATA_RIF'])) {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Bilancio precedente 2 </td>
      <td class="txt1" colspan='12' align='left'>
      	<? echo YMD2DMY($aVar['D_DATA_RIF'])." - ".$aVar['D_DESCR_BIL'];?>
      </td>
   </tr>
<?
	}
	if ($acRat['rb_sigla']=='') {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Rating bilancio</td>
      <td class="txt1" colspan='12' >-- non calcolato --</td>
   </tr>
<?
	} else {
		$sqlSel = "SELECT * FROM rgl_puntbil " 
				." WHERE id_mod_rbil = ".$acRat['id_mod_rbil']
				." AND sigla = '".addslashes($acRat['rb_sigla'])."' ";
		$objDB->query($sqlSel,'selRec');
		$sStyle = '';
		if ($acP = $objDB->fetch('selRec')) {
			if ($acP['colore']=='verde') {
				$sStyle = "color:".RGL_COLORE_VERDE.";";
			} elseif ($acP['colore']=='giallo') {
				$sStyle = "color:".RGL_COLORE_GIALLO.";";
			} else {
				$sStyle = "color:".RGL_COLORE_ROSSO.";";
			}
		} 
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Rating bilancio</td>
      <td class="txt1" colspan='2' align='center'
      	style='font-size:16pt;font-weight:bold;<?=$sStyle?>'><? echo $acRat['rb_sigla'];?></td>
      <td class="txt1" colspan='10' align='left'><? echo $acP['descr_estesa'];?></td>
   </tr>
   <tr>
      <td class="lab1" colspan='10' align='center'>Indice</td>
      <td class="lab1" colspan='2' align='center'>Valore</td>
      <td class="lab1" colspan='4' align='center'>Valutazione</td>
      <td class="lab1" colspan='2' align='center'>Media</td>
      <td class="lab1" colspan='1' align='center'>Punteggio</td>
      <td class="lab1" colspan='1' align='center'>Peso</td>
   </tr>
<?
	$sSql = "SELECT ri.* "
		." FROM rgl_ratbil_indici ri "
		." WHERE ri.id_rating = ".reqVar('id');
	$objDB->query($sSql);
	while ($acRBI = $objDB->fetch()) {
		$codH = "<a href='../cbil/calcDato.php?cd=".$acRBI['cod_dato']
			."&bil1=".$acRat['id_bil']."&bil2=".$acRat['id_bil_2']
			."&xsn=".XSN."' class='txt1'>".$acRBI['cod_dato']."</a>";
		$desH = $aDefDati[$acRBI['cod_dato']]['descr'];
		$valH = number_format($acRBI['valore'],2,',','.')."&nbsp;";
		$medH = number_format($acRBI['media_rif'],2,',','.')."&nbsp;";
		$punH = $acRBI['punteggio']."&nbsp;";
		$pesH = $acRBI['peso']."&nbsp;";		
		if ($acRBI['punteggio'] > 80) {
			$sValutaz = 'molto positivo';
			$sStyle = 'color:'.RGL_COLORE_VERDE.';';
		} elseif ($acRBI['punteggio'] > 60) {
			$sValutaz = 'positivo';
			$sStyle = 'color:'.RGL_COLORE_VERDE.';';
		} elseif ($acRBI['punteggio'] > 30) {
			$sValutaz = 'in media';
			$sStyle = 'color:'.RGL_COLORE_GIALLO.';';
		} elseif ($acRBI['punteggio'] > 10) {
			$sValutaz = 'negativo';
			$sStyle = 'color:'.RGL_COLORE_ROSSO.';';
		} else {
			$sValutaz = 'molto negativo';
			$sStyle = 'color:'.RGL_COLORE_ROSSO.';';
		}
?>
   <tr>
      <td class="txt1" colspan='3' align='left'><?=$codH?></td>
      <td class="txt1" colspan='7' align='left'><?=$desH?></td>
      <td class="txt1" colspan='2' align='right'><?=$valH?></td>
      <td class="txt1" colspan='4' align='center' style="<?=$sStyle?>">
      	<?=$sValutaz?></td>
      <td class="txt1" colspan='2' align='right'><?=$medH?></td>
      <td class="txt1" colspan='1' align='right'><?=$punH?></td>
      <td class="txt1" colspan='1' align='right'><?=$pesH?></td>
   </tr>
<?
		}
	}
}
if ($acRat['cod_mod_rque']!='') {
?>
   <tr>
      <td class="tit1" colspan='20' align='center'>Rating a questionario</td>
   </tr>
   <tr>
      <td class="lab1" colspan='4' align='left'>Modello</td>
      <td class="txt1" colspan='8' align='left'>
      	<? echo $acRat['descr_mod_rque'];?>
      </td>
      <td class="lab1" colspan='1' align='left'>Peso</td>
      <td class="txt1" colspan='1' align='left'>
      	<? echo $acRat['rq_peso'];?>
      <td class="lab1" colspan='1' align='left'>Punt.</td>
      <td class="txt1" colspan='1' align='left'>
      	<? echo $acRat['rq_punteggio'];?>
      </td>
      <td class="txt1" colspan='4' align='left' valign='top' >
 			&nbsp;
      </td>
<?
	if ($acRat['rq_sigla']=='') {
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Rating</td>
      <td class="txt1" colspan='12' >
<?
	$bDaCompilare = true;
	if (!empty($acRat['str_que'])) {
		$aQueRisp = unsgzu($acRat['str_que']);
		$bDaCompilare = false;		
		foreach($aQueRisp as $codSez => $aSez) {
			if (!isset($aSez['c']) || $aSez['c']!='S') {
				$bDaCompilare = true;
				break;
			}
		}
	}
	if ($bDaCompilare) {
   	echo " -- questionario da compilare --";
	} else {
		echo " -- questionario compilato - da calcolare --";
	}	
?>
      </td>
      <td class="txt1" colspan='4'  align='center'>
			<a class='txt1' href='rqueIns.php?id=<?=reqVarInt('id')?>&xsn=<?=XSN?>'>imputa questionario</a>
		</td>
   </tr>
<?
	} else {
		$sqlSel = "SELECT * FROM rgl_puntque " 
				." WHERE id_mod_rque = ".$acRat['id_mod_rque']
				." AND sigla = '".addslashes($acRat['rq_sigla'])."' ";
		$objDB->query($sqlSel,'selRec');
		$sStyle = '';
		if ($acP = $objDB->fetch('selRec')) {
			if ($acP['colore']=='verde') {
				$sStyle = "color:".RGL_COLORE_VERDE.";";
			} elseif ($acP['colore']=='giallo') {
				$sStyle = "color:".RGL_COLORE_GIALLO.";";
			} else {
				$sStyle = "color:".RGL_COLORE_ROSSO.";";
			}
		} 
?>
   <tr>
      <td class="lab1" colspan='4' align='left'>Rating</td>
      <td class="txt1" colspan='2' align='center'
      	style='font-size:16pt;font-weight:bold;<?=$sStyle?>'><? echo $acRat['rq_sigla'];?></td>
      <td class="txt1" colspan='10' align='left'><? echo $acP['descr_estesa'];?></td>
      <td class="txt1" colspan='4' align='center'>
			<a class='txt1' href='rqueVis.php?id=<?=reqVarInt('id')?>&xsn=<?=XSN?>'>visualizza questionario</a>
		</td>
   </tr>
<?
	}
}
?>
</table>
<table border="0" cellpadding="3" cellspacing="1" width="100%" align='center'>
   <tr>
      <td class="cmd1" align="left">
			<? echo $sCmdL; ?>
      </td>
      <td class="cmd1" align="right">
			<? echo $sCmdR; ?>
      </td>
   </tr>
</table>
<?
echo "</form>\n";

codaHtml();
exit();

function registraNotching(&$modoNotching) {
	global $objDB, $objSess;
	$msg = '';
	$modoNotching = 'S';
	if (reqVarInt('noching')!=0 && reqvarTrim('nota_analista')=='') {
		$msg .= "nota obbligatoria";
	}
	if ($msg != '') return $msg;
	
	$sqlSel = "SELECT id_mod_rglob,punt_calc FROM rgl_rating " 
		." WHERE id_rating = ".reqvar('id');
	$objDB->query($sqlSel,'selRec');
	$acRat = $objDB->fetch('selRec');
	$punt = $acRat['punt_calc'] + reqvarInt('notching')*10;
	$sqlSel = "SELECT * FROM rgl_puntglob " 
		." WHERE id_mod_rglob = ".$acRat['id_mod_rglob']
		." ORDER BY punteggio";
	$objDB->query($sqlSel,'selRec');
	$sSigla = '???';
	while ($acP = $objDB->fetch('selRec')) {
   	if ($punt<=$acP['punteggio']) {
      	$sSigla = $acP['sigla'];
      	break;
   	} 
      $sSigla = $acP['sigla'];
	}
	$sSql = "UPDATE rgl_rating SET nota = '".reqvarAS('nota_analista')."'"
				.", punteggio = $punt, sigla = '".addslashes($sSigla)."' "
				.", notching = ".reqvarInt('notching')
				.",data_ora = '".date('Y-m-d H:i:s')."'"
				.",id_utente = ".$objSess->idUtente
				." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$modoNotching = '';
	return 'notching registrato';
}

function resetRatGlob() {
	global $objDB, $objSess;
	$msg = '';
	$sSql = "UPDATE rgl_rating SET stato = 'creato'"
		.", punteggio = 0, punt_calc = 0, sigla = '', sigla_calc = '' "
		.",data_ora = '".date('Y-m-d H:i:s')."'"
		.",id_utente = ".$objSess->idUtente
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$sSql = "UPDATE rgl_ratbil SET  punteggio = 0, sigla = '' "
		.",data_ora = '".date('Y-m-d H:i:s')."'"
		.",id_utente = ".$objSess->idUtente
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$sSql = "DELETE FROM rgl_ratbil_indici "
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$sSql = "UPDATE rgl_ratque SET  punteggio = 0, sigla = '' "
		.",data_ora = '".date('Y-m-d H:i:s')."'"
		.",id_utente = ".$objSess->idUtente
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	
	return 'rating resettato';
}

function calcRatGlob() {
	global $objDB, $objSess;
	$msg = '';
	
	$aVar = array();
	
	$sSql = "SELECT r.*, rb.id_bil, rb.id_bil_2, rb.id_bil_3, mb.tipo_tab_indici "
		.", mg.id_mod_rbil, rb.peso AS peso_rbil, mb.cod_mod_rbil, mb.descr AS mb_descr "
		.", mg.id_mod_rque, rq.peso AS peso_rque, mq.cod_mod_rque, mq.descr AS mq_descr "
		.", mg.descr AS mg_descr "
		." FROM rgl_rating r "
		." LEFT JOIN rgl_mod_rglob mg ON mg.id_mod_rglob = r.id_mod_rglob "
		." LEFT JOIN rgl_mod_rbil mb ON mb.id_mod_rbil = mg.id_mod_rbil "
		." LEFT JOIN rgl_mod_rque mq ON mq.id_mod_rque = mg.id_mod_rque "
		." LEFT JOIN rgl_ratbil rb ON rb.id_rating = r.id_rating "
		." LEFT JOIN rgl_ratque rq ON rq.id_rating = r.id_rating "
		." WHERE r.id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$acRat = $objDB->fetch();
	if (!$acRat) {
		return _t("manca rating bilancio '%s'",reqVar('id'));
	}
	$notching = $acRat['notching']; //salva notching precedentemente imputato
	
	$totPuntPesoGlob = 0;
	$totPesoGlob = 0;
	
	if ($acRat['id_mod_rbil']==0) {
		$sSql = "DELETE FROM rgl_ratbil "
			." WHERE id_rating = ".reqVar('id');
		$objDB->query($sSql);
		$sSql = "DELETE FROM rgl_ratbil_indici "
			." WHERE id_rating = ".reqVar('id');
		$objDB->query($sSql);
	} else {
		$aVar = array();
		$aDefDati = array();
		$msg = aVarCalcTabDati($acRat['id_bil'], $acRat['id_bil_2'], $aVar, $aDefDati, 99);
			
		$sSql = "DELETE FROM rgl_ratbil_indici "
			." WHERE id_rating = ".reqVar('id');
		$objDB->query($sSql);
		
		$sSql = "SELECT pi.* FROM rgl_mod_rbil_par_ind pi "
			." WHERE pi.id_mod_rbil = ".$acRat['id_mod_rbil']
			." AND pi.cod_sett = '".addslashes($acRat['cod_sett'])."' ";
		//dbg_($sSql);
		$objDB->query($sSql,'selParInd');
		$totPuPe = 0;
		$totPe = 0;
		$sCsv = '';
		$sCsv .= "Indice;valore;soglia25;soglia50;soglia75;soglia100;punteggio;peso\r\n";
		$aIndVal = array();
		while ($acPI = $objDB->fetch('selParInd')) {
			$totPe += $acPI['peso'];
			$codInd = "Q_".$acPI['cod_dato'];
			if (!isset($aVar[$codInd])) $valInd = 0;
			else $valInd = floatval($aVar[$codInd]);
			if ($valInd >= $acPI['soglia100']) {
				$puntInd =  100;
			} elseif ($valInd >= $acPI['soglia75']) {
				$puntInd =  75;
			} elseif ($valInd >= $acPI['soglia50']) {
				$puntInd =  50;
			} elseif ($valInd >= $acPI['soglia25']) {
				$puntInd =  25;
			} else {
				$puntInd = 0;
			}
			$totPuPe += $puntInd*$acPI['peso'];
			$sSql = "INSERT INTO rgl_ratbil_indici "
				." (id_rating,cod_dato,valore,media_rif,punteggio,peso) "
				." values(".reqVar('id').",'".addslashes($acPI['cod_dato'])
				."',$valInd,".$acPI['media_rif'].",$puntInd,".$acPI['peso'].")";
			$objDB->query($sSql);	
			$sCsv .= $acPI['cod_dato'].";".number_format($valInd,5,',','')
				.";".number_format($acPI['soglia25'],5,',','')
				.";".number_format($acPI['soglia50'],5,',','')
				.";".number_format($acPI['soglia75'],5,',','')
				.";".number_format($acPI['soglia100'],5,',','')
				.";".$puntInd.";".$acPI['peso']."\r\n";
		}
		$puntRbil = ($totPe!=0)?$totPuPe / $totPe:0;
		$sqlSel = "SELECT * FROM rgl_puntbil " 
			." WHERE id_mod_rbil = ".$acRat['id_mod_rbil']
			." ORDER BY punteggio";
		$objDB->query($sqlSel,'selRecPuBi');
		$sSigla = '???';
		while ($acP = $objDB->fetch('selRecPuBi')) {
	   	if ($puntRbil<=$acP['punteggio']) {
	      	$sSigla = $acP['sigla'];
	      	break;
	   	} 
	      $sSigla = $acP['sigla'];
		}	
		$sSql = "SELECT id_rating FROM rgl_ratbil "
			." WHERE id_rating = ".reqVar('id');
		$objDB->query($sSql);
		if (!$acX=$objDB->fetch()) {
			$sSql = "INSERT INTO rgl_ratbil SET id_rating = ".reqVar('id')
			.",id_bil = ".$acRat['id_bil']
			.",id_bil_2 = ".$acRat['id_bil_2']
			.",id_bil_3 = ".$acRat['id_bil_3']
			.",peso = ".intval($acRat['peso_rbil'])
			.",data_ora = '".date('Y-m-d H:i:s')."'"
			.",id_utente = ".$objSess->idUtente
			.",str_def_dati = '".addslashes(gzcompress(serialize($aDefDati)))."'"
			.",str_dati = '".addslashes(gzcompress(serialize($aVar)))."'"
			.",cod_mod_rbil = '".addslashes($acRat['cod_mod_rbil'])."'"
			.",descr_mod_rbil = '".addslashes($acRat['mb_descr'])."'"
			.",tipo_tab_indici = ".$acRat['tipo_tab_indici']
			;
			$objDB->query($sSql);
		}
		$sSql = "UPDATE rgl_ratbil SET punteggio = $puntRbil "
			.",sigla = '".addslashes($sSigla)."'"
			.",data_ora = '".date('Y-m-d H:i:s')."'"
			.",id_utente = ".$objSess->idUtente
			.",str_def_dati = '".addslashes(gzcompress(serialize($aDefDati)))."'"
			.",str_dati = '".addslashes(gzcompress(serialize($aVar)))."'"
			.",cod_mod_rbil = '".addslashes($acRat['cod_mod_rbil'])."'"
			.",descr_mod_rbil = '".addslashes($acRat['mb_descr'])."'"
			.",tipo_tab_indici = ".$acRat['tipo_tab_indici']
			." WHERE id_rating = ".reqVar('id')
			;
		$objDB->query($sSql);
		
		$totPuntPesoGlob += $puntRbil * $acRat['peso_rbil'];
		$totPesoGlob += $acRat['peso_rbil'];
	} 

	//rating a questionario
	if ($acRat['id_mod_rque']==0) {
		$sSql = "DELETE FROM rgl_ratque "
			." WHERE id_rating = ".reqVar('id');
		$objDB->query($sSql);
	} else {
		//lettura risposte memorizzate
		$aQueRisp = array();
		$sqlSel = "SELECT rq.str_que  FROM rgl_ratque rq " 
				." WHERE rq.id_rating = ".reqVar('id');
		$objDB->query($sqlSel,'selRec');
		$acRQ = $objDB->fetch('selRec');
		$bDaCompilare = true;
		if ($acRQ && !empty($acRQ['str_que'])) {
			$aQueRisp = unsgzu($acRQ['str_que']);
			$bDaCompilare = false;		
			foreach($aQueRisp as $codSez => $aSez) {
				if (!isset($aSez['c']) || $aSez['c']!='S') {
					$bDaCompilare = true;
					break;
				}
			}
		}
		if ($bDaCompilare) {
			$sSql = "UPDATE rgl_ratque SET punteggio = 0 "
				.",sigla = ''"
				.",data_ora = '".date('Y-m-d H:i:s')."'"
				.",id_utente = ".$objSess->idUtente
				.",cod_mod_rque = '".addslashes($acRat['cod_mod_rque'])."'"
				.",descr_mod_rque = '".addslashes($acRat['mq_descr'])."'"
				." WHERE id_rating = ".reqVar('id')
				;
			$objDB->query($sSql);
		} else {
			$totPe = 0;
			$totPuPe = 0;
			//dbg_($aQueRisp);
			foreach($aQueRisp as $codSez => $aSez) {
				$totSezPe = 0;
				$totSezPuPe = 0;
				foreach($aSez['a'] as $codDom => $aDom) {
					$totSezPe += $aDom['p'];
					$totSezPuPe += $aDom['v']*$aDom['p'];
					//dbg_("$codSez.$codDom=".$aDom['v']."/".$aDom['p']);
				}
				$puntSez = ($totSezPe!=0)?$totSezPuPe / $totSezPe:0;	
				$totPe += $aSez['p'];
				$totPuPe += $puntSez*$aSez['p'];
			}							
			$puntRque = ($totPe!=0)?$totPuPe / $totPe:0;				
	
			$sqlSel = "SELECT * FROM rgl_puntque " 
				." WHERE id_mod_rque = ".$acRat['id_mod_rque']
				." ORDER BY punteggio";
			$objDB->query($sqlSel,'selRecPuBi');
			$sSigla = '???';
			while ($acP = $objDB->fetch('selRecPuBi')) {
		   	if ($puntRque<=$acP['punteggio']) {
		      	$sSigla = $acP['sigla'];
		      	break;
		   	} 
		      $sSigla = $acP['sigla'];
			}	
			if (!$acRQ) {
				$sSql = "INSERT INTO rgl_ratque SET id_rating = ".reqVar('id')
				.",peso = ".intval($acRat['peso_rque'])
				.",data_ora = '".date('Y-m-d H:i:s')."'"
				.",id_utente = ".$objSess->idUtente
				.",cod_mod_rque = '".addslashes($acRat['cod_mod_rque'])."'"
				.",descr_mod_rque = '".addslashes($acRat['mq_descr'])."'"
				;
				$objDB->query($sSql);
			}
			$sSql = "UPDATE rgl_ratque SET punteggio = $puntRque "
				.",sigla = '".addslashes($sSigla)."'"
				.",data_ora = '".date('Y-m-d H:i:s')."'"
				.",id_utente = ".$objSess->idUtente
				.",cod_mod_rque = '".addslashes($acRat['cod_mod_rque'])."'"
				.",descr_mod_rque = '".addslashes($acRat['mq_descr'])."'"
				." WHERE id_rating = ".reqVar('id')
				;
			$objDB->query($sSql);
								
			$totPuntPesoGlob += $puntRque * $acRat['peso_rbil'];
			$totPesoGlob += $acRat['peso_rbil'];				
		}
	}		
		
		
	$puntCalc = ($totPesoGlob!=0)?($totPuntPesoGlob/$totPesoGlob):0;
	$sqlSel = "SELECT * FROM rgl_puntglob " 
		." WHERE id_mod_rglob = ".$acRat['id_mod_rglob']
		." ORDER BY punteggio";
	$objDB->query($sqlSel,'selSogliePunt');
	$sSiglaCalc = '???';
	while ($acP = $objDB->fetch('selSogliePunt')) {
   	if ($puntCalc<=$acP['punteggio']) {
      	$sSiglaCalc = $acP['sigla'];
      	break;
   	} 
      $sSiglaCalc = $acP['sigla'];
	}
	$punteggio = $puntCalc + 10 * $notching;
	$sSigla = '???';
	$objDB->seekFirst('selSogliePunt');
	while ($acP = $objDB->fetch('selSogliePunt')) {
   	if ($punteggio<=$acP['punteggio']) {
      	$sSigla = $acP['sigla'];
      	break;
   	} 
      $sSigla = $acP['sigla'];
	}
	$sSql = "UPDATE rgl_rating SET punt_calc = $puntCalc "
		.", punteggio = $punteggio "
		.", sigla_calc = '".addslashes($sSiglaCalc)."'"
		.", sigla = '".addslashes($sSigla)."'"
		.", data_rif = '".$aVar['B_DATA_RIF']."' "
		.", stato = 'calcolato' "
		.",data_ora = '".date('Y-m-d H:i:s')."'"
		.",id_utente = ".$objSess->idUtente
		.",cod_mod_rglob = '".addslashes($acRat['cod_mod_rglob'])."'"
		.",descr_mod_rglob = '".addslashes($acRat['mg_descr'])."'"
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	
	file_put_contents(RGL_FS_LOG_DIR."/ratg_".reqVar('id').".csv",$sCsv);
	
	return "rating calcolato";
}

function elimRatGlob() {
	global $objDB, $objSess;
	$msg = '';
	$sSql = "DELETE FROM rgl_ratbil "
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$sSql = "DELETE FROM rgl_rating "
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$sSql = "DELETE FROM rgl_ratbil_indici "
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	$sSql = "DELETE FROM rgl_ratque "
		." WHERE id_rating = ".reqVar('id');
	$objDB->query($sSql);
	
	header("Location: ".urlTorna('rating eliminato'));
	exit();
}
